package org.aceor.tennis.web.util;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aceor.tennis.common.exception.BusinessRuntimeException;
import org.aceor.tennis.web.dto.BaseResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Slf4j
public class WebUtil {

    public static void writeJsonResponse(HttpServletResponse resp,
                                         Map<String, Object> data) {
        writeJsonResponse(resp, JSON.toJSONString(data));
    }

    public static <T> void writeJsonResponse(HttpServletResponse resp,
                                             BaseResult<T> obj) {
        writeJsonResponse(resp, JSON.toJSONString(obj));
    }

    public static void writeJsResponse(HttpServletResponse response, String msg, String href) {
        try {
            response.setContentType("text/html; charset=utf-8");
            PrintWriter wrt = response.getWriter();
            wrt.write("<script>alert('" + msg + "');location.href='" + href + "';</script>");
            wrt.close();
        } catch (IOException e) {
            throw new BusinessRuntimeException(e.getLocalizedMessage());
        }

    }

    public static void writeJsonResponse(HttpServletResponse res, String jsonStr) {
        try {
            res.setContentType("text/html;charset=UTF-8");
            res.setCharacterEncoding("UTF-8");
            PrintWriter wrt = res.getWriter();
            wrt.write(jsonStr);
            wrt.flush();
            wrt.close();
        } catch (IOException e) {
            throw new BusinessRuntimeException(e.getLocalizedMessage());
        }
    }

    public static String attainErrorInfoFromBindingResult(BindingResult bindingResult) {
        List<String> errors = Lists.newLinkedList();
        for (Object object : bindingResult.getAllErrors()) {
            if (object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;
                //这里有乱码日狗了
                errors.add(fieldError.getField() + ":" + fieldError.getDefaultMessage());
            }

            if (object instanceof ObjectError) {
                ObjectError objectError = (ObjectError) object;
                //暂时ignore,一般就取字段校验结果,即FieldError
            }
        }
        return errors.isEmpty() ? "" : Joiner.on(",").join(errors);
    }

}
